import Util from '../../utils/util.js';
import {delAddress, editAddress, getAddressDetail, getAddressList, getUserInfo} from '../../api/member.js';
import {bind_phone} from "../../api/api";

let app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    btnActive: true,

    multiIndex: [0, 0, 0],
    province_id: 0,
    city_id: 0,
    region_id: 0,
    multiIds: [],
    newArr: [],

    bedArr: {},
    bedIndex: 0,

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const that = this;
    this.setData({...options})

    wx.showLoading({
      title: "正在加载..."
    })
    Util.chekWxLogin().then(res => {
      wx.hideLoading()
      that.setData({
        member: res.userInfo,
        supplier_id: wx.getStorageSync("shop_supplier_id")
      })

      if (!Util.isEmpty(that.data.address_id)) {
        getAddressDetail(that.data.address_id || '')
          .then(res => {
            that.setData({
              address: res.data.address || "",
              member: res.data.member || null,
            })
            that.showSelectArea();
          }).catch(errmsg => {
          app.Tips({title: errmsg})
        })
      } else {
        that.showSelectArea();
      }

      that.loadUserInfo();

    }).catch(errmsg => {
      app.Tips({title: errmsg})
    })

    this.onLoadTabbar();
  },

  bindChange(e) {
    this.setData({
      bedIndex: e.detail.value || 0
    })
  },

  showSelectArea(e) {
    const that = this
    // let areas = wx.getStorageSync("addressList");
    let areas = null;
    if (!areas) {
      getAddressList().then(res => {
        // wx.setStorageSync('addressList', res.data.addressList);
        that.setData(res.data)
        that.initAddress();
      })
    } else {
      that.setData({addressList: areas})
      this.initAddress();
    }
  },

  initAddress() {

    const that = this,
      address = this.data.address;

    let state = {
      arr: [],
      arr1: [],
      arr2: [],
      arr3: [],
      multiIds: []
    }

    if (address) {
      state.multiIds.push(address.province_id)
      state.multiIds.push(address.city_id)
      state.multiIds.push(address.region_id)

      this.data.addressList.map((v, vk) => {
        if (v.id !== state.multiIds[0]) {
          return;
        }
        that.data.multiIndex[0] = vk;
        that.setData({multiIndex: that.data.multiIndex})

        v._child.map((c, ck) => {
          if (c.id !== state.multiIds[1]) {
            return;
          }
          that.data.multiIndex[1] = ck;

          that.setData({multiIndex: that.data.multiIndex})
          c._child.map((t, tk) => {
            if (t.id !== state.multiIds[2]) {
              return;
            }
            that.data.multiIndex[2] = tk;

            if (!Util.isEmpty(t._child)) {
              that.setData({
                bedArr: t._child
              })

              that.data.bedArr.map((bed, bk) => {
                if (bed.id == address.district) {
                  that.setData({
                    bedIndex: bk
                  })
                  return
                }
              })
            }
          });
        })
        that.setData({multiIndex: that.data.multiIndex})
      })
    }

    this.data.addressList.map((v, vk) => {
      state.arr1.push(v.title);
      if (that.data.multiIndex[0] == vk) {
        state.multiIds[0] = v['id'];
        that.data.province_id = v['id'];

        if (state.arr2.length <= 0) {
          v._child.map((c, ck) => {
            state.arr2.push(c.title);

            if (this.data.multiIndex[1] === ck) {
              // state.multiIds[1] = c;
              state.multiIds[1] = c['id'];
              this.data.city_id = c['id'];

              if (state.arr3.length <= 0) {
                c._child.map((t, tk) => {
                  state.arr3.push(t.title);
                  if (this.data.multiIndex[2] === tk) {
                    // state.multiIds[2] = t;
                    state.multiIds[2] = t['id'];
                    this.data.region_id = t['id'];

                    if (Util.isEmpty(t._child))
                      return;

                    this.setData({
                      bedArr: t._child || null,
                      bedIndex: 0
                    })
                  }
                });
              }
            }
          });
        }
      }
    });

    state.arr[0] = state.arr1;
    state.arr[1] = state.arr2;
    state.arr[2] = state.arr3;

    this.setData({
      newArr: state.arr,
      multiIds: state.multiIds,
    });
  },

  bindMultiPickerChange(e) {

  },

  loadUserInfo() {
    let that = this;
    getUserInfo().then(res => {
      that.setData({
        member: res.data,
      });
      console.log(this.data.member)
    }).finally(() => {
    })
  },

  bindMultiPickerColumnChange(e) {
    const that = this;

    let data = {
      newArr: this.data.newArr,
      multiIndex: this.data.multiIndex,
      multiIds: this.data.multiIds,
    };

    data.multiIndex[e.detail.column] = e.detail.value;
    let searchColumn = () => {
      let arr1 = [];
      let arr2 = [];
      this.data.addressList.map((v, vk) => {

        if (data.multiIndex[0] === vk) {
          /*data.multiIds[0] = {
            ...v,
          };*/
          data.multiIds[0] = v['id'];
          this.data.province_id = v['id'];

          that.setData({
            bedArr: {},
            bedIndex: 0,
          })

          v._child.map((c, ck) => {
            arr1.push(c.title);
            if (data.multiIndex[1] === ck) {
              /*data.multiIds[1] = {
                ...c,
              };*/
              data.multiIds[1] = c['id'];
              this.data.city_id = c['id'];

              if (Util.isEmpty(c._child)) {
                return;
              }

              c._child.map((t, vt) => {
                arr2.push(t.title);
                if (data.multiIndex[2] === vt) {
                  /*data.multiIds[2] = {
                    ...t,
                  };*/
                  data.multiIds[2] = t['id'];
                  this.data.region_id = t['id'];

                  that.setData({
                    bedArr: t._child || null,
                  })
                }
              });
            }
          });
        }
      });
      data.newArr[1] = arr1;
      data.newArr[2] = arr2;
    };

    switch (e.detail.column) {
      case 0:
        // 每次切换还原初始值
        data.multiIndex[1] = 0;
        data.multiIndex[2] = 0;
        // 执行函数处理
        searchColumn();
        break;
      case 1:
        data.multiIndex[2] = 0;
        searchColumn();
        break;
      case 2:
        searchColumn();
        break;
    }
    this.setData(data);
  },

  /**
   * 表单提交
   */
  formSubmit: function (e) {

    let that = this,
      formData = e.detail.value;

    if (Util.isEmpty(formData.consignee)) {
      app.Tips({title: "联系人必填", hideMask: true});
      return
    }
    if (Util.isEmpty(formData.phone)) {
      app.Tips({title: "手机号必填", hideMask: true});
      return
    }
    if (!Util.checkIphone(formData.phone)) {
      app.Tips({title: "手机号格式错误", hideMask: true});
      return;
    }
    if (Util.isEmpty(this.data.province_id)) {
      app.Tips({title: "楼栋必选", hideMask: true});
      return
    }
    if (Util.isEmpty(this.data.city_id)) {
      app.Tips({title: "楼层必选", hideMask: true});
      return
    }
    if (Util.isEmpty(this.data.region_id)) {
      app.Tips({title: "科室必选", hideMask: true});
      return
    }

    let address = this.data.newArr[0][this.data.multiIndex[0]]
      + this.data.newArr[1][this.data.multiIndex[1]]
      + this.data.newArr[2][this.data.multiIndex[2]]

    //床号
    if (!Util.isEmpty(this.data.bedArr) && !Util.isEmpty(this.data.bedArr[this.data.bedIndex])) { //病患需要地址
      formData['district'] = this.data.bedArr[this.data.bedIndex].id;
      address += parseInt(this.data.bedArr[this.data.bedIndex].title) ? (this.data.bedArr[this.data.bedIndex].title + "床") : this.data.bedArr[this.data.bedIndex].title
    }

    if (!this.data.btnActive)
      return false;

    if (formData['address'])
      address += " " + formData['address']

    formData['province_id'] = this.data.province_id;
    formData['city_id'] = this.data.city_id;
    formData['region_id'] = this.data.region_id;

    if (!Util.isEmpty(this.data.address)) {
      formData['id'] = this.data.address.id
    }

    Util.showModelTip(address, "确认收货地址", "确定", "").then(res => {
      if (res.confirm) {
        that.setData({btnActive: false})
        wx.showLoading({title: "正在更新..."})
        editAddress(formData).then(res => {
          that.setData({btnActive: true})

          wx.setStorageSync("address_id", res.data.id)
          wx.setStorageSync("is_refresh", 1)
          app.Tips({title: that.data.address_id ? '更新成功' : '新增成功'}, {tab: 3})
        }).catch(errmsg => {
          that.setData({btnActive: true})
          app.Tips({title: errmsg})
        })

      }
    })

  },

  delAddress(e) {
    const that = this,
      address = that.data.address;
    if (Util.isEmpty(address)) {
      return Util.Tips({title: "当前地址不可删除"})
    }

    Util.showModelTip("确认删除", "确定", "").then(res => {
      if (res.confirm) {
        wx.showLoading({title: "正在删除..."})
        delAddress({id: address.id}).then(res => {
          wx.setStorageSync("is_refresh", 1)
          Util.Tips({title: "删除成功"}, {tab: 3})
        }).catch(errmsg => {
          Util.Tips({title: errmsg})
        })
      }
    })
  },

  getPhoneNumber(e) {
    const that = this;
    if (e.detail.errMsg == 'getPhoneNumber:fail user deny') {
      return app.Tips({
        title: "取消授权",
        icon: "error",
        hideMaskClose: true
      })
    } else if (e.detail.errMsg == 'getPhoneNumber:ok') {
      let param = e.detail;
      bind_phone(param).then(res => {
        wx.setStorageSync('is_refresh', 1)
        that.setData({
          phone: res.data.mobile || ""
        })
      }).catch(errmsg => {
        return app.Tips({title: errmsg})
      })
    }
  },

  /**
   * 修改地区
   */
  bindRegionChange: function (e) {
    this.setData({
      region: e.detail.value
    })
  },

  onLoadTabbar: function () {//底部tabbar返回数据
    const that = this

    Util.checkIphone().then(res => {//检查是否是iphone x/11等
      that.setData({isIphoneX: res})
      wx.createSelectorQuery().in(that).select('.weui-footer')
        .boundingClientRect(function (rect) {
          if (!rect) return;
          let bottom = parseInt(rect.height) + 15;
          if (that.data.isIphoneX) {
            bottom += 20;
          }
          that.setData({
            bottom: bottom
          })
        }).exec()
    });
  },

})